package base_util

import (
	"github.com/jinzhu/copier"
	"github.com/shopspring/decimal"
	"go-likaladi-shop/common/base_global"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func LogicError(errorMsg string) error {
	return status.Errorf(codes.Code(base_global.CustomErrorCode), errorMsg)
}

func LogicCodeError(code int, errorMsg string) error {
	return status.Errorf(codes.Code(code), errorMsg)
}

func GrpcCodeError(code codes.Code, err error) error {
	return status.Errorf(code, err.Error())
}

func GrpcCodeErrorMsg(code codes.Code, errorMsg string) error {
	return status.Errorf(code, errorMsg)
}

func GrpcError(err error) error {
	zap.S().Errorw("程序异常", "错误消息", err)
	return status.Errorf(codes.Internal, err.Error())
}

func Copy(source any, target any) error {
	errorMsg := "Copy对象属性异常"
	if err := copier.Copy(target, source); err != nil {
		zap.S().Errorw(errorMsg, "错误消息", err)
		return LogicError(errorMsg)
	}
	return nil
}

func FormatDecimal(data string) (decimal.Decimal, error) {
	errorMsg := "字符串转Decimal异常"
	// 转换 string -> decimal.Decimal
	d, err := decimal.NewFromString(data)
	if err != nil {
		zap.S().Errorw(errorMsg, "错误消息", err)
		return decimal.Decimal{}, LogicError(errorMsg)
	}
	return d, nil
}
